#include "mpi.h"
#include <stdio.h>
#include <complex.h>
#include <math.h>


int nprocs; /* Number of processors */
int myid; /* My rank */

int global_sum(int partial) {
	/* Implement your own global summation here */
	MPI_Status status;
	int mydone;
	int hisdone;
	int partner;
	int l;
	mydone = partial;
	
	for(l = 0; l < (int)log2(nprocs); l++){
		partner = myid^(int)pow(2, l);
		//printf("partner = %d\n", partner);
		MPI_Send(&mydone, 1, MPI_INT, partner, 10, MPI_COMM_WORLD);
		MPI_Recv(&hisdone, 1, MPI_INT, partner, 10, MPI_COMM_WORLD, &status);
		mydone = mydone + hisdone;
	}
	
	return mydone;
}

int main(int argc, char *argv[]) {
	int partial, sum;
	MPI_Init(&argc, &argv);
	MPI_Comm_rank(MPI_COMM_WORLD, &myid);
	MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
	partial = myid + 1;
	printf("Node %d has %d\n", myid, partial);
	sum = global_sum(partial);
	if (myid == 0) printf("Global sum = %d\n", sum);
	MPI_Finalize();
}


